package com.elong.android.specialhouse.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.dp.android.elong.crash.LogWriter;
import com.elong.android.specialhouse.IConfig;
import com.elong.android.specialhouse.R;
import com.elong.infrastructure.concurrent.ICustomDialog;

public class CustomDialogBuilder implements ICustomDialog, View.OnClickListener {

	public final static int WIDTH_FIXED = 0;
	public final static int WIDTH_FILLPARENT = 1;
	public final static int WIDTH_WRAPCONTENT = 2;

	public final static int ID_MAINVIEW = 0;
	public final static int ID_TITLE_CONTAINER = 1;
	public final static int ID_TITLE = 2;
	public final static int ID_MESSAGE = 3;
	public final static int ID_CONTENTVIEW = 4;
	public final static int ID_POSITIVEBUTTON = 5;
	public final static int ID_NEGATIVEBUTTON = 6;
	public final static int ID_ELONGLOGOANIM = 7;

	public final static int ID_COLSE_BUTTON = 7;

	public final static int BUTTON_POSITIVE = 0;
	public final static int BUTTON_NEGATIVE = 1;
	public final static int BUTTON_CLOSE = 2;

	public static final int LOADINGDYNAMICTIPS[] = { R.string.loadingDynamicTips10, R.string.loadingDynamicTips10,
			R.string.loadingDynamicTips10, R.string.loadingDynamicTips10, R.string.loadingDynamicTips10,
			R.string.loadingDynamicTips10, R.string.loadingDynamicTips10, R.string.loadingDynamicTips10,
			R.string.loadingDynamicTips10, R.string.loadingDynamicTips10 };

	public final static int[] LOADING_DIALOG_IDS = { R.layout.dialog_loading, R.id.dialog_title_container,
			R.id.dialog_title, R.id.dialog_message, R.id.dialog_contentview, R.id.dialog_positive_button,
			R.id.dialog_negative_button, R.id.dialog_close_button, };
	
	public final static int[] DIALOG_IDS = { R.layout.dialog_normal, R.id.dialog_title_container,
		R.id.dialog_title, R.id.dialog_message, R.id.dialog_contentview, R.id.dialog_positive_button,
		R.id.dialog_negative_button, R.id.dialog_close_button, };
	private static final String TAG = "CustomDialogBuilder";

	private Context m_context;
	private Dialog m_dialog;

	private View m_mainView;
	private View m_titleContainer;
	private TextView m_title;
	private TextView m_message;
	private ViewGroup m_contentView;
	private View m_positiveButton;
	private DialogInterface.OnClickListener m_positiveButtonListener;
	private View m_negativeButton;
	private DialogInterface.OnClickListener m_negativeButtonListener;
	private DialogInterface.OnClickListener m_closeButtonListener;
	private int m_widthType;
	private Validator m_validator;
	private Observer m_observer;
	private View m_closeButton;

	// private ProgressBar mProgressVertical;
	// private int mProgressStatus = 0;
	// private Handler mHandler = new Handler();

	// type 0 is loading dialog
	public CustomDialogBuilder(Context context, int[] compoentIds, int type) {
		init(context, compoentIds, type);
		/*
		 * if(m_context != context) { init(context,compoentIds); }
		 */
		reset();

	}

	// type 0 is loading dialog
	private void init(Context context, int[] compoentIds, int type) {
		m_context = context;
		m_dialog = new Dialog(m_context);

		// remove dialog title.
		m_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// set dialog background to transparent to hide system UI feature.
		Window window = m_dialog.getWindow();
		window.setBackgroundDrawable(new ColorDrawable(m_context.getResources().getColor(android.R.color.transparent)));
		LayoutInflater inflater = LayoutInflater.from(m_context);
		m_mainView = inflater.inflate(compoentIds[ID_MAINVIEW], null);
		m_dialog.setContentView(m_mainView);

		m_titleContainer = m_mainView.findViewById(compoentIds[ID_TITLE_CONTAINER]);
		m_title = (TextView) m_mainView.findViewById(compoentIds[ID_TITLE]);
		m_message = (TextView) m_mainView.findViewById(compoentIds[ID_MESSAGE]);
		m_contentView = (ViewGroup) m_mainView.findViewById(compoentIds[ID_CONTENTVIEW]);
		m_positiveButton = m_mainView.findViewById(compoentIds[ID_POSITIVEBUTTON]);

		if (m_positiveButton != null) {
			m_positiveButton.setOnClickListener(this);
		}
		m_negativeButton = m_mainView.findViewById(compoentIds[ID_NEGATIVEBUTTON]);

		if (m_negativeButton != null) {
			m_negativeButton.setOnClickListener(this);
		}

		m_closeButton = m_mainView.findViewById(compoentIds[ID_COLSE_BUTTON]);
		if (m_closeButton != null) {
			m_closeButton.setOnClickListener(this);
		}
		// 屏蔽Search按钮，防止用户取消Loading框
		m_dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false; // 默认返回 false
				}
			}
		});
	}

	private void reset() {
		if (m_titleContainer != null) {
			m_titleContainer.setVisibility(View.GONE);
		}

		if (m_title != null) {
			m_title.setVisibility(View.GONE);
			m_title.setText(null);
		}

		if (m_message != null) {
			m_message.setVisibility(View.GONE);
			m_message.setText(null);
		}

		if (m_contentView != null) {
			m_contentView.setVisibility(View.GONE);
		}

		if (m_positiveButton != null) {
			m_positiveButton.setVisibility(View.GONE);
		}

		if (m_negativeButton != null) {
			m_negativeButton.setVisibility(View.GONE);
		}
		m_positiveButtonListener = null;
		m_negativeButtonListener = null;
	}

	public Context getContext() {
		return m_context;
	}

	public void setTitle(String title) {
		if (title != null) {
			m_titleContainer.setVisibility(View.VISIBLE);
			m_title.setVisibility(View.VISIBLE);
			m_title.setText(title);
		}
	}

	public void setTitle(int resId) {
		setTitle(m_context.getString(resId));
	}

	public void setMessage(String message) {
		if (message != null && m_message != null) {
			m_message.setVisibility(View.VISIBLE);
			// Debug 模式下显示信息可以滑动
			if (IConfig.DEBUG_ON) {
				m_message.setMovementMethod(ScrollingMovementMethod.getInstance());
			}
			m_message.setText(message);
		}
	}

	public void setMessage(int resId) {
		setMessage(m_context.getString(resId));
	}

	public void setContentView(View view) {
		if (view != null) {
			m_contentView.setVisibility(View.VISIBLE);
			m_contentView.removeAllViews();
			m_contentView.addView(view);
		}
	}

	public ViewGroup getContentContainer() {
		return m_contentView;
	}

	public void setPositiveButton(String text, DialogInterface.OnClickListener listener) {
		m_positiveButton.setVisibility(View.VISIBLE);
		((TextView) m_positiveButton).setText(text);
		m_positiveButtonListener = listener;
	}

	public void setPositiveButton(int resId, DialogInterface.OnClickListener listener) {
		setPositiveButton(m_context.getString(resId), listener);
	}

	public void setNegativeButton(String text, DialogInterface.OnClickListener listener) {
		m_negativeButton.setVisibility(View.VISIBLE);
		((TextView) m_negativeButton).setText(text);
		m_negativeButtonListener = listener;
	}

	public void setCloseButton(DialogInterface.OnClickListener listener) {
		m_closeButton.setVisibility(View.VISIBLE);
		m_closeButtonListener = listener;
	}

	public void setNegativeButton(int resId, DialogInterface.OnClickListener listener) {
		setNegativeButton(m_context.getString(resId), listener);
	}

	public void setObserver(Observer observer) {
		m_observer = observer;
	}

	public Dialog getDialog() {
		return m_dialog;
	}

	/*
	 * private DialogInterface.OnCancelListener m_onCancelListener; public void
	 * setOnCancelListener(DialogInterface.OnCancelListener listener) {
	 * m_onCancelListener = listener; }
	 */

	public void setWidthType(int type) {
		m_widthType = type;
	}

	public View getButton(int button) {
		if (button == BUTTON_POSITIVE) {
			return m_positiveButton;
		} else if (button == BUTTON_NEGATIVE) {
			return m_negativeButton;
		}
		return null;
	}

	public void setGravity(int gravity) {
		m_dialog.getWindow().setGravity(gravity);
	}

	public void show() {
		// Activity已死
		if (m_observer != null && !m_observer.isAlive()) {
			return;
		}

		if (m_dialog.isShowing())
			return;

		Window window = m_dialog.getWindow();
		WindowManager.LayoutParams params = window.getAttributes();
		switch (m_widthType) {
		case WIDTH_FIXED:
		case WIDTH_FILLPARENT:
			window = m_dialog.getWindow();
			params = window.getAttributes();
			params.width = window.getWindowManager().getDefaultDisplay().getWidth()
					- (m_widthType == WIDTH_FIXED ? 40 : 0);
			window.setAttributes(params);
			break;
		}

		try {
			m_dialog.show();
		} catch (Exception e) {
			LogWriter.logException(TAG, LogWriter.LOG_LEVEL_ERROR, e);
		}

	}

	public void dismiss() {
		// Activity已死
		if (m_observer != null && !m_observer.isAlive()) {
			return;
		}

		if (!m_dialog.isShowing())
			return;

		if (this.m_context instanceof Activity && ((Activity) this.m_context).isFinishing()) {
			return;
		}

		try {
			m_dialog.dismiss();
		} catch (Exception e) {
			LogWriter.logException(TAG, LogWriter.LOG_LEVEL_WARNING, e);
		}

	}

	public void onClick(View view) {
		if (view == m_positiveButton) {
			if (m_validator != null && !m_validator.validate(BUTTON_POSITIVE)) {
				return;
			}
			
			if (m_positiveButtonListener != null) {
				m_positiveButtonListener.onClick(m_dialog, Dialog.BUTTON_POSITIVE);
			}
		} else if (view == m_negativeButton) {
			if (m_validator != null && !m_validator.validate(BUTTON_NEGATIVE)) {
				return;
			}
			
			if (m_negativeButtonListener != null) {
				m_negativeButtonListener.onClick(m_dialog, Dialog.BUTTON_NEGATIVE);
			}
		} else if (view == m_closeButton) {
			if (m_validator != null && !m_validator.validate(BUTTON_CLOSE)) {
				return;
			}
			
			if (m_closeButtonListener != null) {
				m_closeButtonListener.onClick(m_dialog, Dialog.BUTTON_NEGATIVE);
			}
		}
		dismiss();
	}

	public void setValidator(Validator validator) {
		m_validator = validator;
	}

	public void setCancelable(boolean cancelable) {
		if (m_dialog != null) {
			m_dialog.setCancelable(cancelable);
		}
	}

	public interface Validator {
		public boolean validate(int button);
	}

	public interface Observer {
		public boolean isAlive();
	}

	public boolean isShowing() {
		return m_dialog.isShowing();
	}
}
